package p06_DAO;

import bean.Customer;

import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;

/**
 * CustomerDAO的实现类
 */
public class CustomerDAOImpl extends BaseDAO<Customer> implements CustomerDAO {

    @Override
    public int insert(Connection conn, Customer customer) throws SQLException {
        String sql = "insert into customers (name, email, birth) values (?,?,?)";
        return modify(
                sql,
                conn,
                customer.getName(),
                customer.getEmail(),
                customer.getBirth()
        );
    }

    @Override
    public int deleteById(Connection conn, int id) throws SQLException {
        String sql = "delete from customers where id = ?";
        return modify(sql, conn, id);
    }

    @Override
    public int update(Connection conn, Customer customer) throws SQLException {
        String sql = "update customers set name = ?, email = ?, birth = ? where id = ?";
        return modify(
                sql,
                conn,
                customer.getName(),
                customer.getEmail(),
                customer.getBirth(),
                customer.getId()
        );
    }

    @Override
    public Customer getCustomerById(Connection conn, int id) {
        String sql = "select id, name, email, birth from customers where id = ?";
        return query(conn, sql, id).get(0);
    }

    @Override
    public List<Customer> getAllCustomers(Connection conn) {
        String sql = "select id, name, email, birth from customers";
        return query(conn, sql);
    }

    @Override
    public long getCount(Connection conn) {
        String sql = "select count(*) from customers";
        return (long) getValue(conn, sql);
    }

    @Override
    public Date getMaxBirth(Connection conn) {
        String sql = "select max(birth) from customers";
        return (Date) getValue(conn, sql);
    }
}
